﻿using System.DirectoryServices.ActiveDirectory;
using PathologyBLL.Service;
using PathologyDAL.Modle;
using PathologyDAL.Service;
using Sunny.UI;

namespace Pathology.UI
{
    public partial class FilterManagePage : UIPage
    {
        public FilterManagePage()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 这个页面添加的类型
        /// </summary>
        public Filter FormFilter { get; set; }

        private ConditionManageServicels services;

        private void FilterManagePage_InitializeAsync(object sender, EventArgs e)
        {
            services = new ConditionManageServicels(FormFilter);

            // LoadItems();

            //加载数据库中已经有的东西
            LoadExitsItem();
        }

        private async void LoadExitsItem()
        {
            var list = await services.LoadEffictivItems(uiTextBoxFilter.Text);

            LoaduiListBoxItems(list);
        }

        public void LoaduiListBoxItems(List<FilterCondition> filterConditions)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(() =>
                {
                    uiListBoxItems.Items.Clear();
                    foreach (FilterCondition item in filterConditions)
                    {
                        uiListBoxItems.Items.Add(item);
                    }
                });
            }
            else
            {
                uiListBoxItems.Items.Clear();
                foreach (FilterCondition item in filterConditions)
                {
                    uiListBoxItems.Items.Add(item);
                }
            }
        }

        //检查输入的名称

        private bool Frm_CheckedData(object sender, UIEditForm.EditFormEventArgs e)
        {
            if (e.Form["Name"] == null)
            {
                return false;
            }
            string name = e.Form["Name"].ToString().Trim();

            //检查输入的文字是否有重复
            var list = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            if (list.Length != list.Distinct().Count())
            {
                this.ShowErrorTip($"输入的名称有重复，请重新输入！", 2000);
                return false;
            }

            return Task.Run(async () =>
            {
                string filterConditions = await services.CheckExistAsync(name);
                if (filterConditions.Length == 0)
                {
                    return true;
                }
                else
                {
                    this.ShowErrorTip($"[{filterConditions}]已存在，请重新输入！", 2000);
                    return false;
                }
            }).Result;
        }

        private bool Frm_CheckedUpdateData(object sender, UIEditForm.EditFormEventArgs e)
        {
            string name = e.Form["Name"].ToString().Trim();

            if (name.Contains(" "))
            {
                this.ShowErrorTip($"修改模式下不支持多输入！", 2000);
                return false;
            }
            return Task.Run(async () =>
            {
                string filterConditions = await services.CheckExistAsync(e.Form["Name"].ToString());
                if (filterConditions.Length == 0)
                {
                    return true;
                }
                else
                {
                    this.ShowErrorTip($"[{filterConditions}]已存在，请重新输入！", 2000);
                    return false;
                }
            }).Result;
        }

        private void uiRadioButtonGroupPossibility_ValueChanged(
            object sender,
            int index,
            string text
        )
        {
            
            
            
            if (null == currentFilter)
            {
                return;
            }
            //更改了按钮
            DisPlayTransferSet(index + 1, uiTextBoxFilterTumour.Text);
        }

        private async void DisPlayTransferSet(int index, string filterString)
        {
            uiTransferSet.ItemsLeft.Clear();
            uiTransferSet.ItemsRight.Clear();
            if (null == currentFilter)
            {
                return;
            }
            TransferSetContainer transferSetContainer = new TransferSetContainer();

            if (index == 0)
            {
                return;
            }
            else
            {
                transferSetContainer = await services.GetTumourDisPlayForTransferSetAsync(
                    currentFilter,
                    (Possibility)index
                );
            }

            //开始显示
            if (string.IsNullOrEmpty(filterString))
            {
                if (null != transferSetContainer.Left)
                {
                    uiTransferSet.ItemsLeft.AddRange(transferSetContainer.Left.ToArray());
                }
                if (null != transferSetContainer.Right)
                {
                    uiTransferSet.ItemsRight.AddRange(transferSetContainer.Right.ToArray());
                }
            }
            else
            {
                if (null != transferSetContainer.Left)
                {
                    uiTransferSet.ItemsLeft.AddRange(
                        transferSetContainer
                            .Left.Where(t => t.Name.Contains(filterString))
                            .ToArray()
                    );
                }
                if (null != transferSetContainer.Right)
                {
                    uiTransferSet.ItemsRight.AddRange(
                        transferSetContainer
                            .Right.Where(t => t.Name.Contains(filterString))
                            .ToArray()
                    );
                }
            }
        }

        private void uiTextBoxFilter_TextChanged(object sender, EventArgs e)
        {
            LoadExitsItem();
        }

        //点击了新增按钮
        private async void uiSymbolButtonAdd_ClickAsync(object sender, EventArgs e)
        {
            //  FilterCondition filterCondition = new FilterCondition();
            // filterCondition.Empty = true;
            var displayLable = AttributeValueTool.GetDisplayLable<Filter>(FormFilter.ToString());

            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            option.Text = $"新增[{displayLable}]";

            option.AddText("Name", "名称", null, true);

            UIEditForm frm = new UIEditForm(option);
            frm.Render();
            frm.CheckedData += Frm_CheckedData;
            frm.ShowDialog();

            if (frm.IsOK)
            {
                //处理逻辑
                await Task.Run(async () =>
                {
                    string Names = frm["Name"].ToString();
                    if (!string.IsNullOrEmpty(Names))
                    {
                        string message = await services.AddConditionAsync(Names.Trim());
                        this.ShowInfoTip(message, 2000);
                        LoadExitsItem();
                    }
                });
            }

            frm.Dispose();
        }

        private async void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            if (uiListBoxItems.SelectedIndex > -1)
            {
                FilterCondition filterCondition = (FilterCondition)uiListBoxItems.SelectedItem;
                if (null != filterCondition)
                {
                    var displayLable = AttributeValueTool.GetDisplayLable<Filter>(
                        FormFilter.ToString()
                    );
                    UIEditOption option = new UIEditOption();
                    option.AutoLabelWidth = true;
                    option.Text = $"修改[{displayLable}]";
                    option.AddText("Name", "名称:", filterCondition.Name, true);
                    UIEditForm frm = new UIEditForm(option);
                    frm.Render();
                    frm.CheckedData += Frm_CheckedUpdateData;
                    frm.ShowDialog();

                    if (frm.IsOK)
                    {
                        //处理逻辑

                        //处理逻辑
                        await Task.Run(async () =>
                        {
                            string Names = frm["Name"].ToString();

                            if (!string.IsNullOrEmpty(Names))
                            {
                                string message = await services.UpdateAsync(
                                    Names.Trim(),
                                    filterCondition
                                );
                                this.ShowInfoTip(message, 2000);
                                LoadExitsItem();
                            }
                        });
                    }

                    frm.Dispose();
                }
            }
        }

        private async void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            if (uiListBoxItems.SelectedIndex > -1)
            {
                if (this.ShowAskDialog("确认删除！"))
                {
                    FilterCondition filterCondition = (FilterCondition)uiListBoxItems.SelectedItem;
                    if (null != filterCondition)
                    {
                        string message = await services.DeleteAsync(filterCondition.Id);
                        //从数据库中删除和肿瘤的关联
                       
                        this.ShowInfoTip(message, 2000);

                        LoadExitsItem();
                    }
                }
            }
        }

        private void uiSymbolButton4_Click(object sender, EventArgs e)
        {
            uiRadioButtonGroupPossibility.SelectedIndex = -1;
            uiTextBoxFilterTumour.Clear();
            LoadExitsItem();
        }

        private FilterCondition currentFilter;

        private void uiListBoxItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            //修改了选择

            if (uiListBoxItems.SelectedIndex > -1)
            {
                FilterCondition filterCondition = (FilterCondition)uiListBoxItems.SelectedItem;
                if (null != filterCondition)
                {
                    //清除选择
                    uiTransferSet.ItemsLeft.Clear();
                    uiTransferSet.ItemsRight.Clear();
                    uiRadioButtonGroupPossibility.SelectedIndex = -1;
                    currentFilter = filterCondition;
                }
            }
        }

        private void uiTextBoxFilterTumour_TextChanged(object sender, EventArgs e)
        {
            DisPlayTransferSet(
                uiRadioButtonGroupPossibility.SelectedIndex + 1,
                uiTextBoxFilterTumour.Text
            );
        }

        private async void uiTransferSet_ItemsRightCountChangeAsync(object sender, EventArgs e)
        {
            //只要保证右侧的被添加


            if (null == currentFilter)
            {
                return;
            }

            List<int> rigthTumour = new List<int>();
            foreach (var item in uiTransferSet.ItemsRight)
            {
                Tumour? t = item as Tumour;
            
                if (null != t)
                {
                    rigthTumour.Add(t.ID);
                }
            }
            //左侧的，只要不正左侧显示的被移除就可以


            List<int> leftTumour = new List<int>();
            foreach (var item in uiTransferSet.ItemsLeft)
            {
                Tumour? t = item as Tumour;
                if (null != t)
                {
                    leftTumour.Add(t.ID);
                }
            }
            await services.SaveTransFerSeRigthChangesAsync(
                rigthTumour,
                currentFilter,
                uiRadioButtonGroupPossibility.SelectedIndex + 1
            );
            await services.SaveTransFerSeLeftChangesAsync(
                leftTumour,
                currentFilter,
                uiRadioButtonGroupPossibility.SelectedIndex + 1
            );
        }
    }
}
